package tcm.com.gistone.controller;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import tcm.com.gistone.database.config.GetBySqlMapper;
import tcm.com.gistone.database.entity.GroupBook;
import tcm.com.gistone.database.entity.GroupWord;
import tcm.com.gistone.database.entity.Word;
import tcm.com.gistone.database.mapper.GroupBookMapper;
import tcm.com.gistone.database.mapper.GroupWordMapper;
import tcm.com.gistone.database.mapper.WordMapper;
import tcm.com.gistone.util.ClientUtil;
import tcm.com.gistone.util.EdatResult;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * Created by qiang on 2017/11/25.
 */
@RestController
@RequestMapping( "group" )
@Transactional
public class GroupController {
    private final static org.slf4j.Logger logger = LoggerFactory.getLogger(ClientUtil.class);
    @Autowired
    private GroupBookMapper groupBookMapper;
    @Autowired
    private GroupWordMapper groupWordMapper;
    @Autowired
    private GetBySqlMapper getBySqlMapper;
    @Autowired
    private WordMapper wm;

    /**
     * @Author:renqiang
     * @Param:
     * @Description:根据专题或者分组
     * @Date:15:49 2017/11/25
     */
    @RequestMapping( value = "selectGroupBySpecial", method = RequestMethod.POST )
    public EdatResult selectGroupBySpecial(HttpServletRequest request, HttpServletResponse response) throws IOException {
        try {
            ClientUtil.SetCharsetAndHeader(request, response);
            JSONObject data = JSONObject.fromObject(request.getParameter("data"));
            long specialID = data.getLong("specialID");//专题id
            String sql = "select distinct group_name from tb_book_group where special_id =" + specialID;
            return EdatResult.ok(getBySqlMapper.findRecords(sql));
        } catch (Exception e) {
            return EdatResult.build(1, "操作失败");
        }
    }

    /**
     * @Author:renqiang
     * @Param:
     * @Description:根据分组查询类型
     * @Date:18:21 2017/11/25
     */
    @RequestMapping( value = "selectTypeByGroup", method = RequestMethod.POST )
    public EdatResult selectTypeByGroup(HttpServletRequest request, HttpServletResponse response) throws IOException {
        try {
            ClientUtil.SetCharsetAndHeader(request, response);
            JSONObject data = JSONObject.fromObject(request.getParameter("data"));
            String groupName = data.getString("groupName");//分组名称
            String sql = "select distinct type_name from tb_book_group where group_name ='" + groupName + "'";
            return EdatResult.ok(getBySqlMapper.findRecords(sql));
        } catch (Exception e) {
            return EdatResult.build(1, "操作失败");
        }
    }

    /**
     * @Author:renqiang
     * @Param:
     * @Description:查询分组中的文献
     * @Date:15:53 2017/11/25
     */
    @RequestMapping( value = "selectBookByGruop", method = RequestMethod.POST )
    public Map selectBookByGruop(HttpServletRequest request, HttpServletResponse response) throws IOException {
        try {
            ClientUtil.SetCharsetAndHeader(request, response);
            JSONObject data = JSONObject.fromObject(request.getParameter("data"));
            String groupName = request.getParameter("groupName");//分组名称
            int pageSize = Integer.parseInt(request.getParameter("pageSize"));
            int pageNumber = Integer.parseInt(request.getParameter("pageNumber"));
            Map map = new HashMap();
            map.put("page", pageNumber);
            if (groupName.equals("")) {
                map.put("total", 0);
                map.put("rows", new ArrayList<>());
                return map;
            }
            String sql1 = "select count(T1.id) from tb_group_book T1,tb_bookinfo T2 where group_name = '" + groupName + "' and T1.book_id = T2.book_id ";
            map.put("total", getBySqlMapper.findrows(sql1));
            String sql = "select T1.*,T2.book_name from(select TT1.*,TT2.type_id from (select * from tb_group_book where group_name = '" + groupName + "' )" + " TT1 join tb_book_group TT2 on TT1.type_name = TT2.type_name )T1  join tb_bookinfo T2 on T1.book_id = T2.book_id " + " order by type_id asc,book_name asc,time  asc limit " + pageNumber + "," + pageSize;
            map.put("rows", getBySqlMapper.findRecords(sql));
            return map;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /*根据名称查找分组信息*/
    @RequestMapping( value = "selectBySpecial", method = RequestMethod.POST )
    public EdatResult selectBySpecial(HttpServletRequest request, HttpServletResponse response) throws IOException {
        try {
            ClientUtil.SetCharsetAndHeader(request, response);
            JSONObject data = JSONObject.fromObject(request.getParameter("data"));
            long specialId = data.getLong("specialID");//专题id
            String keyword = data.getString("keyword");//关键词
            String group = data.getString("group");//分组名称
            String type = data.getString("type");//类型名称
            int dataType = data.getInt("dataType");//1查询书籍分组，2查询关键词分组
            String sql = "";
            if (dataType == 1) {
                sql = "select book_id,book_name from tb_bookinfo T1 where T1.special_id = " + specialId + " and T1.status = 7 and T1.book_name like '%" + keyword + "%'  AND " + " not EXISTS (select * from tb_group_book where group_name = '" + group + "' and type_name = '" + type + "'  and  book_id = T1.book_id  )";
            } else {
                sql = "select word_id,word from tb_word T1 where T1.parent_id = T1.word_id and  T1.special_id = " + specialId + "  and T1.word like '%" + keyword + "%'  AND " + "not EXISTS (select * from tb_group_word where group_name = '" + group + "' and type_name = '" + type + "'  and  word_id = T1.word_id  )";
            }
            return EdatResult.ok(getBySqlMapper.findRecords(sql));
        } catch (Exception e) {
            e.printStackTrace();
            return EdatResult.build(1, "操作失败");
        }
    }

    /**
     * @Author:renqiang
     * @Param:
     * @Description:添加分组
     * @Date:18:21 2017/11/25
     */
    @RequestMapping( value = "addGroupBook", method = RequestMethod.POST )
    public EdatResult addGroupBook(HttpServletRequest request, HttpServletResponse response) throws IOException {
        try {
            ClientUtil.SetCharsetAndHeader(request, response);
            JSONObject data = JSONObject.fromObject(request.getParameter("data"));
            String grourName = data.getString("groupName");//
            JSONArray bookIDs = data.getJSONArray("bookIDs");//
            String type = data.getString("type");//
            for (int i = 0; i < bookIDs.size(); i++) {
                long bookID = bookIDs.getLong(i);
                String sql = " INSERT INTO tb_group_book (group_name,type_name,book_id,time) SELECT '" + grourName + "','" + type + "'," + bookID + ",SYSDATE() FROM dual" + "  WHERE not exists (select * from tb_group_book where group_name= '" + grourName + "' and type_name = '" + type + "' and book_id = " + bookID + ");";
                getBySqlMapper.insert(sql);
            }
            return EdatResult.ok();
        } catch (Exception e) {
            e.printStackTrace();
            return EdatResult.build(1, "操作失败");
        }
    }

    /**
     * @Author:renqiang
     * @Param:
     * @Description:删除
     * @Date:18:21 2017/11/25
     */
    @RequestMapping( value = "deleteGroupBook", method = RequestMethod.POST )
    public EdatResult deleteGroupBook(HttpServletRequest request, HttpServletResponse response) throws IOException {
        try {
            ClientUtil.SetCharsetAndHeader(request, response);
            JSONObject data = JSONObject.fromObject(request.getParameter("data"));
            long ID = data.getLong("ID");
            groupBookMapper.deleteByPrimaryKey(ID);
            return EdatResult.ok();
        } catch (Exception e) {
            return EdatResult.build(1, "操作失败");
        }
    }


    /**
     * @Author:renqiang
     * @Param:
     * @Description:根据专题或者分组
     * @Date:15:49 2017/11/25
     */
    @RequestMapping( value = "selectGroupBySpecial1", method = RequestMethod.POST )
    public EdatResult selectGroupBySpecial1(HttpServletRequest request, HttpServletResponse response) throws IOException {
        try {
            ClientUtil.SetCharsetAndHeader(request, response);
            JSONObject data = JSONObject.fromObject(request.getParameter("data"));
            long specialID = data.getLong("specialID");//专题id
            String sql = "select distinct group_name from tb_word_group where special_id =" + specialID;
            return EdatResult.ok(getBySqlMapper.findRecords(sql));
        } catch (Exception e) {
            return EdatResult.build(1, "操作失败");
        }
    }

    /**
     * @Author:renqiang
     * @Param:
     * @Description:根据分组查询类型
     * @Date:18:21 2017/11/25
     */
    @RequestMapping( value = "selectTypeByGroup1", method = RequestMethod.POST )
    public EdatResult selectTypeByGroup1(HttpServletRequest request, HttpServletResponse response) throws IOException {
        try {
            ClientUtil.SetCharsetAndHeader(request, response);
            JSONObject data = JSONObject.fromObject(request.getParameter("data"));
            String groupName = data.getString("groupName");//
            String sql = "select distinct  type_name from tb_word_group where group_name ='" + groupName + "'";
            return EdatResult.ok(getBySqlMapper.findRecords(sql));
        } catch (Exception e) {
            return EdatResult.build(1, "操作失败");
        }
    }

    /**
     * @Author:renqiang
     * @Param:
     * @Description:查询分组中的文献
     * @Date:15:53 2017/11/25
     */
    @RequestMapping( value = "selectWordByGruop", method = RequestMethod.POST )
    public Map selectWordByGruop(HttpServletRequest request, HttpServletResponse response) throws IOException {
        try {
            ClientUtil.SetCharsetAndHeader(request, response);
            String groupName = request.getParameter("groupName");
            String specialID = request.getParameter("specialID");
            int pageSize = Integer.parseInt(request.getParameter("pageSize"));
            int pageNumber = Integer.parseInt(request.getParameter("pageNumber"));
            Map map = new HashMap();
            map.put("page", pageNumber / pageSize);
            if (groupName.equals("")) {
                map.put("total", 0);
                map.put("rows", new ArrayList<>());
                return map;
            }
            String sql = "select * from (select * from (select T1.*,T2.word from(select * from tb_group_word where group_name = '" + groupName + "')T1 join tb_word T2 on T1.word_id = T2.word_id " + " )T3 order by type_name asc,time desc,word asc) T4 limit " + pageNumber + "," + pageSize;
            String sql1 = "select count(*) from tb_group_word T1,tb_word T2 where T1.group_name = '" + groupName + "' and  T1.word_id = T2.word_id ";
            System.out.println(sql);
            map.put("total", getBySqlMapper.findrows(sql1));
            map.put("rows", getBySqlMapper.findRecords(sql));
            return map;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /*根据名称查找文献*/
    @RequestMapping( value = "selectWordBySpecial", method = RequestMethod.POST )
    public EdatResult selectWordBySpecial(HttpServletRequest request, HttpServletResponse response) throws IOException {
        try {
            ClientUtil.SetCharsetAndHeader(request, response);
            JSONObject data = JSONObject.fromObject(request.getParameter("data"));
            long specialId = data.getLong("specialID");//专题id
            String sql = "select word_id,word from tb_word where special_id = " + specialId;
            return EdatResult.ok(getBySqlMapper.findRecords(sql));
        } catch (Exception e) {
            return EdatResult.build(1, "操作失败");
        }
    }

    /**
     * @Author:renqiang
     * @Param:
     * @Description:分组内添加主题词
     * @Date:18:21 2017/11/25
     */
    @RequestMapping( value = "addGroupWord", method = RequestMethod.POST )
    public EdatResult addGroupWord(HttpServletRequest request, HttpServletResponse response) throws IOException {
        try {
            ClientUtil.SetCharsetAndHeader(request, response);
            JSONObject data = JSONObject.fromObject(request.getParameter("data"));
            String groupName = data.getString("groupName");//
            JSONArray bookIDs = data.getJSONArray("wordIDs");//
            String type = data.getString("type");//
            for (int i = 0; i < bookIDs.size(); i++) {
                long wordID = bookIDs.getLong(i);
                String sql = " INSERT INTO tb_group_word(group_name,type_name,word_id,time) SELECT '" + groupName + "','" + type + "'," + wordID + ",SYSDATE() FROM dual" + "  WHERE not exists (select * from tb_group_word where group_name= '" + groupName + "' and type_name = '" + type + "' and word_id = " + wordID + ")";
                getBySqlMapper.insert(sql);
            }
            return EdatResult.ok();
        } catch (Exception e) {
            e.printStackTrace();
            return EdatResult.build(1, "操作失败");
        }
    }

    /**
     * @Author:renqiang
     * @Param:
     * @Description:删除分组内主题词
     * @Date:18:21 2017/11/25
     */
    @RequestMapping( value = "deleteGroupWord", method = RequestMethod.POST )
    public EdatResult deleteGroupWord(HttpServletRequest request, HttpServletResponse response) throws IOException {
        try {
            ClientUtil.SetCharsetAndHeader(request, response);
            JSONObject data = JSONObject.fromObject(request.getParameter("data"));
            long ID = data.getLong("ID");
            groupWordMapper.deleteByPrimaryKey(ID);
            return EdatResult.ok();
        } catch (Exception e) {
            return EdatResult.build(1, "操作失败");
        }
    }

    /*查询主题词*/
    @RequestMapping( value = "selectWord", method = RequestMethod.POST )
    public Map selectWord(HttpServletRequest request, HttpServletResponse response) {
        try {
            ClientUtil.SetCharsetAndHeader(request, response);
            int pageNumber = Integer.parseInt(request.getParameter("pageNumber"));
            int pageSize = Integer.parseInt(request.getParameter("pageSize"));
            String keyWord = request.getParameter("keyWord");/*关键词*/
            long specialId = Long.parseLong(request.getParameter("specialId"));
            long wordType = Long.parseLong(request.getParameter("wordType"));/*主题词类型*/
            String sql = "";
            String sql3 = "";
            if (!keyWord.equals("")) {
                sql3 = " and word like '%" + keyWord + "%'";
            }
            /*查询主词*/
            sql = "select distinct parent_id as id  from tb_word where special_id = " + specialId + " and theme_type = " + wordType + sql3 + "  order by word asc limit " + pageNumber + "," + pageSize;
            List<Map> result = getBySqlMapper.findRecords(sql);
            if (result.size() < 1) {
                return null;
            }
            for (int i = 0; i < result.size(); i++) {
                long id = (long) result.get(i).get("id");
                /*查询别名*/
                String sql2 = "select word from tb_word where  parent_id = " + id + " and word_id != " + id;
                Word word = wm.selectByPrimaryKey(id);
                List<Map> res = new ArrayList<>();
                res = getBySqlMapper.findRecords(sql2);
                String str = "";/*别名，逗号隔开*/
                for (int j = 0; j < res.size(); j++) {
                    if (j == 0) {
                        str += res.get(j).get("word");
                    } else {
                        str += "," + res.get(j).get("word");
                    }
                }
                result.get(i).put("word", word.getWord());
                result.get(i).put("alias", str);/*别名*/
                result.get(i).put("url", word.getPicUrl() == null ? "" : word.getPicUrl());/*图片路径*/
            }
            String sql1 = "select count(distinct parent_id) as total from tb_word where special_id = " + specialId + " and theme_type = " + wordType + sql3;
            int total = getBySqlMapper.findrows(sql1);
            Map map = new HashMap();
            map.put("total", total);
            map.put("rows", result);
            map.put("page", pageNumber / pageSize);
            return map;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


}
